﻿using JmShared;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SuperWebSocket;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using WebSocketServer.Managers;
using WebSocketServer.models;
using WebSocketServer.Models;
using WebSocketServer.Utilities;

namespace WebSocketServer
{
    public class JiveAppServer : WebSocketServer<JiveClientSession>
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        //private readonly object _lockObject = new object();
        private PushMessageManager _pushMessageManager;
        private EmailManager _emailManager;
        private System.Timers.Timer _databaseCleanupTimer;
        private System.Timers.Timer _unauthorizedUsersCleanupTimer;

        public JiveAppServer()
        {
            _pushMessageManager = new PushMessageManager();
            _emailManager = new EmailManager();
            InitDatabaseCleanupTimer();
            InitUnauthorizedUsersCleanupTimer();

        }


        public void InitUnauthorizedUsersCleanupTimer()
        {
            _unauthorizedUsersCleanupTimer = new System.Timers.Timer();
            _unauthorizedUsersCleanupTimer.Interval = 1000 * 30;//once per 30 seconds
            _unauthorizedUsersCleanupTimer.Elapsed += _unauthorizedUsersCleanupTimer_Elapsed;
            _unauthorizedUsersCleanupTimer.Start();
        }

        void _unauthorizedUsersCleanupTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _unauthorizedUsersCleanupTimer.Enabled = false;
            try
            {
                foreach (JiveClientSession session in this.GetAllSessions())
                {
                    if (session.Connected && (!session.IsLoggedIn || !session.IsReadyToReceiveMessages) && session.StartTime.Subtract(DateTime.Now).TotalSeconds > 30)
                    {
                        session.Close(SuperSocket.SocketBase.CloseReason.ServerClosing); //Close the connection if the user is still not logged in after 30 seconds.
                        log.Info(String.Format("**{0}**  failed to authenticate, closing session.", session.RemoteEndPoint));
                    }
                }
            }
            finally
            {
                _unauthorizedUsersCleanupTimer.Enabled = true;
            }
        }

        private void InitDatabaseCleanupTimer()
        {
            _databaseCleanupTimer = new System.Timers.Timer();
            _databaseCleanupTimer.Interval = 1000 * 60 * 60 * 24; //once per 24 hours
            _databaseCleanupTimer.Elapsed += _databaseCleanupTimer_Elapsed;
            _databaseCleanupTimer.Start();
        }

        void _databaseCleanupTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DB.DbManager.CleanupExpiredGroupMessages();
        }
        public override string JsonSerialize(object target)
        {
            var settings = new JsonSerializerSettings()
            {
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
            };
            settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
            return JsonConvert.SerializeObject(target, settings);
        }
        public override object JsonDeserialize(string json, Type type)
        {
            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
            };
            settings.Converters.Add(new StringEnumConverter { CamelCaseText = true });
            return JsonConvert.DeserializeObject(json, type, settings);
        }
        protected override void OnStartup()
        {
            base.OnStartup();
            StartTilePushTimer();
            StartSendEmailTimer();
            string SqlServer = System.Configuration.ConfigurationManager.AppSettings["SqlServer"];
            string SqlUsername = System.Configuration.ConfigurationManager.AppSettings["SqlUsername"];
            string SqlDatabase = System.Configuration.ConfigurationManager.AppSettings["SqlDatabase"];
            string SqlPort = System.Configuration.ConfigurationManager.AppSettings["SqlPort"];
            string SqlPassword = System.Configuration.ConfigurationManager.AppSettings["SqlPassword"];
            string storedMessagePassPhrase = System.Configuration.ConfigurationManager.AppSettings["StoredMessagePassPhrase"];
            DB.DbManager = new DatabaseManager(SqlServer, SqlUsername, SqlDatabase, SqlPort, SqlPassword, storedMessagePassPhrase);
        }

        protected override void OnStopped()
        {
            base.OnStopped();
            StopTilePushTimer();
            StopSendEmailTimer();
            StopAllPushServices();
        }
        protected override void OnNewSessionConnected(JiveClientSession session)
        {
            base.OnNewSessionConnected(session);

            //try
            //{
            //    Task t = Task.Factory.StartNew(() =>
            //        {
            //            using (EventWaitHandle tmpEvent = new ManualResetEvent(false))
            //            {
            //                tmpEvent.WaitOne(TimeSpan.FromSeconds(30));//Wait 30 seconds
            //            }


            //            if ( session.Connected && (!session.IsLoggedIn || !session.IsReadyToReceiveMessages))
            //            {
            //                session.Close(SuperSocket.SocketBase.CloseReason.ServerClosing); //Close the connection if the user is still not logged in after 30 seconds.
            //                log.Info(String.Format("**{0}**  failed to authenticate, closing session.", session.RemoteEndPoint));
            //            }

            //        });

            //}
            //catch (Exception err)
            //{
            //    log.Error("Exception in connection established handler", err);
            //}
        }


        protected override void OnSessionClosed(JiveClientSession session, SuperSocket.SocketBase.CloseReason reason)
        {
            base.OnSessionClosed(session, reason);
            try
            {
                Console.WriteLine(String.Format("**{0}** has disconnected: {1}", session.RemoteEndPoint, reason.ToString()));
                ChatClient client;
                if (!Clients.ConnectedClients.TryGetValue(session, out client))
                {
                    log.Info("Could not find client, dropping out of OnSessionClosed");
                    return;
                }

                if (client.DeviceType.IsMobileClient())
                    client.StoreDeliveredMessageCount();

                if (!Clients.RemoveConnectedClient(session))
                {
                    log.Info("Failed to remove chat client from dictionary");
                }
                if (!Clients.ConnectedClientsByUserID.ContainsKey(client.UserID))
                {
                    client.UpdateDeviceSync(client.LastMessageSyncTime, false,session.IsLoggedIn);
                    ServerInfoMessage msg = new ServerInfoMessage { UserInfo = client.User, MessageType = ServerInfoMessageType.ContactDisconnected };
                    SendToAll(msg, session, false, true);
                }
                client.CurrentSession = null;
            }
            catch (Exception err)
            {
                log.Error("Exception in connection closed handler", err);
            }
        }

        public void StopAllPushServices()
        {
            this._pushMessageManager.StopAllServices();
        }

        public void StartTilePushTimer()
        {
            _pushMessageManager.StartTilePushTimer();
        }
        public void StopTilePushTimer()
        {
            _pushMessageManager.StopTilePushTimer();
        }
        public void StartSendEmailTimer()
        {
            _emailManager.StartSendMailTimer();
        }
        public void StopSendEmailTimer()
        {
            _emailManager.StopSendMailTimer();
        }
        /// <summary>
        /// Send a DeviceStatus message to all online contacts in a members friend list.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="sender"></param>
        /// <param name="includeMe"></param>
        /// <param name="includeMobile"></param>
        public void SendToAll(DeviceStatus msg, JiveClientSession sender, bool includeMe, bool includeMobile)
        {
            ChatClient senderClient = Clients.ConnectedClients[sender];
            ClientStatus originalStatus = msg.ClientStatus.GetValueOrDefault(ClientStatus.Offline);
            //lock (_lockObject)
            //{
            var friends = senderClient.FriendsList.Select(x => x.Username).ToList();
            if (includeMe)
                friends.Add(sender.ChatClient.Username);

            foreach (string username in friends)
            {
                ConcurrentDictionary<string, ChatClient> receiverClientsForUser;
                if (Clients.ConnectedClientsByNameAndDeviceID.TryGetValue(username, out receiverClientsForUser))
                {
                    ClientStatus? overriddenClientStatus = sender.ChatClient.GetOverriddenClientStatusForUser(username);
                    if (overriddenClientStatus.HasValue)
                        msg.ClientStatus = overriddenClientStatus.Value;
                    foreach (KeyValuePair<string, ChatClient> kvp in receiverClientsForUser)
                    {
                        try
                        {
                            ChatClient receiver = kvp.Value;
                            JiveClientSession receiverSession = receiver.CurrentSession;

                            DeviceType type = receiver.DeviceType;
                            if (!includeMobile && type.IsMobileClient())
                                continue;

                            receiverSession.SendDeviceStatus(msg);
                        }
                        catch (Exception err)
                        {
                            log.Error("Error sending device status message : ", err);
                        }
                    }
                    msg.ClientStatus = originalStatus;
                }
            }
            //}
        }
        /// <summary>
        /// Send a ServerInfoMessage message to all online contacts in a members friend list.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="sender"></param>
        /// <param name="includeMe"></param>
        /// <param name="includeMobile"></param>
        public void SendToAll(ServerInfoMessage msg, JiveClientSession sender, bool includeMe, bool includeMobile)
        {
            ChatClient senderClient = sender.ChatClient;

            //lock (_lockObject)
            //{
            var friends = senderClient.FriendsList.Select(x => x.Username).ToList();
            friends.Add(sender.ChatClient.Username);

            foreach (string username in friends)
            {
                ConcurrentDictionary<string, ChatClient> receiverClientsForUser;

                if (Clients.ConnectedClientsByNameAndDeviceID.TryGetValue(username, out receiverClientsForUser))
                {

                    ClientStatus? overriddenClientStatus = sender.ChatClient.GetOverriddenClientStatusForUser(username);
                    if (overriddenClientStatus.HasValue)
                    {
                        UserInfo user = msg.UserInfo.Clone();

                        user.ClientStatus = overriddenClientStatus.Value;
                        msg.UserInfo = user;
                    }
                    foreach (KeyValuePair<string, ChatClient> kvp in receiverClientsForUser)
                    {
                        if (!includeMe && kvp.Key == sender.ChatClient.DeviceID && kvp.Value.Username == sender.ChatClient.Username)
                            continue;
                        try
                        {
                            ChatClient receiver = kvp.Value;
                            JiveClientSession receiverSession = receiver.CurrentSession;
                            if (receiverSession == null)
                                continue;

                            DeviceType type = receiver.DeviceType;
                            if (!includeMobile && type.IsMobileClient())
                                continue;

                            if (receiverSession.IsLoggedIn && receiverSession.Connected)
                            {
                                receiverSession.SendServerInfoMessage(msg);
                            }
                        }
                        catch (Exception err)
                        {
                            log.Error("Error sending group chat message : ", err);
                        }

                    }

                }
            }
            //}
        }

        /// <summary>
        /// Sends a message to members of the specified group
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="groupID"></param>
        /// <param name="sender"></param>
        /// <param name="includeMobile"></param>
        public void SendToGroup(ChatMessage msg, string groupID, JiveClientSession sender, bool includeMobile)
        {
            ChatClient senderClient = Clients.ConnectedClients[sender];
            //lock (_lockObject)
            //{
            HashSet<Friend> friends = senderClient.FriendsList;
            var recipients = friends.Select(x => x.Username).ToList();
            recipients.Add(sender.ChatClient.Username);
            
            foreach (string username in recipients)
            {
                ConcurrentDictionary<string, ChatClient> clients;
                if (Clients.ConnectedClientsByNameAndDeviceID.TryGetValue(username, out clients))
                {
                    foreach (KeyValuePair<string, ChatClient> kvp in clients.Where(x => x.Value.User.ChatGroups.Any(g => g.ID == groupID)))
                    {
                        if (kvp.Key == sender.ChatClient.DeviceID && kvp.Value.Username == sender.ChatClient.Username)
                            continue;
                        try
                        {
                            ChatClient receiverClient = kvp.Value;

                            var blockedGroups = receiverClient.UserSettings.BlockedGroups;
                            if (blockedGroups != null && receiverClient.UserSettings.BlockedGroups.Any(x => x == groupID))
                                continue;
                            if (!includeMobile && receiverClient.DeviceType.IsMobileClient())
                                continue;

                            if (receiverClient.CurrentSession.SendMessage(msg))
                            {
                                receiverClient.LastMessageSyncTime = msg.MessageRelayTime;

                                this.TrySendToastMessage(senderClient, receiverClient, msg);
                            }
                            if (msg.MessageType == MessageType.GroupMessage)
                            {
                                receiverClient.LastGroupMessageReceivedTime = DateTime.UtcNow;
                                receiverClient.UpdateDeviceSync();
                            }

                            if (ValidToastUnreadMessage(receiverClient, msg))
                            {
                                receiverClient.ReceivedMessageCount++;
                                if (!receiverClient.UnreadMessageStats.ContainsKey(groupID))
                                {
                                    string groupName = receiverClient.User.ChatGroups.FirstOrDefault(grp => grp.ID == groupID).Name;
                                    receiverClient.UnreadMessageStats[groupID] = new UnreadUserMessages()
                                    {
                                        LastReceivedMessageTime = msg.MessageRelayTime.Value,
                                        SenderUsername = groupName,
                                        SenderNickname = groupName,
                                        UnreadMessageCount = 1
                                    };
                                }
                                else
                                {
                                    receiverClient.UnreadMessageStats[groupID].UnreadMessageCount++;
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            log.Error("Error sending group chat message : ", err);
                        }
                    }
                }
            }
            //}
        }
        /// <summary>
        /// Checks if a ChatMessage should count towards a clients unread message count.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool ValidToastUnreadMessage(ChatClient client, ChatMessage msg)
        {
            DeviceType type = client.DeviceType;
            return (type.IsMobileClient())
                && (client.IsActive.GetValueOrDefault(true) == false)
                && (client.IsTilePushActive)
                && (msg.MessageType == MessageType.GroupMessage || msg.MessageType == MessageType.PrivateMessage);
        }
        /// <summary>
        /// Checks if a toast notifications should be sendt for this ChatMessage.
        /// </summary>
        /// <param name="recipient"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private bool ValidateToastPush(ChatClient recipient, ChatMessage msg)
        {
            if (msg.MessageType != MessageType.PrivateMessage && msg.MessageType != MessageType.GroupMessage)
                return false;
            bool validToastPushRecipient = recipient.IsToastPushActive;
            if (!validToastPushRecipient)
                return false;
            UserInfo sender = Clients.ConnectedClientsByUserID[msg.SenderID].User;
            DateTime lastWritten = recipient.LastGroupMessageReceivedTime;
            bool validTimeout = DateTime.UtcNow.Subtract(lastWritten).TotalSeconds >= 120;
            bool validUser = sender.UserName != recipient.User.UserName;
            bool validInactive = recipient.IsActive.GetValueOrDefault(true) == false;
            bool validNotOnPc = !Clients.ConnectedClients.Values.Any(x => x.User.UserName == sender.UserName
                                                                   && x.DeviceType == DeviceType.PC
                                                                   && (x.User.ClientStatus != ClientStatus.Afk));//== ClientStatus.Available || x.Value.User.ClientStatus == ClientStatus.Busy));
            switch (msg.MessageType)
            {
                case MessageType.GroupMessage:
                    return validTimeout && validUser && validInactive && validNotOnPc;
                case MessageType.PrivateMessage:
                    return validUser && validInactive;
                default:
                    return false;
            }
        }
        /// <summary>
        /// Attempt to send a toast notification to the online client.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="recipient"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool TrySendToastMessage(ChatClient sender, ChatClient recipient, ChatMessage msg)
        {
            if (ValidateToastPush(recipient, msg))
            {
                _pushMessageManager.SendToastPush(recipient.PushUri, sender.User.PrettyName, msg);
                return true;
            }
            else
                return false;
        }
        /// <summary>
        /// Attempt to send a toast notification to the offline client.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="recipient"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool TrySendToastMessage(ChatClient sender, OfflineClient recipient, ChatMessage msg)
        {
            _pushMessageManager.SendToastPush(recipient.PushUri, sender.User.PrettyName, msg);
            return true;
        }

        public bool TrySendEmail(string msg, string subject, string toEmailAddress, string toName = null)
        {
            string fromEmailAddress = System.Configuration.ConfigurationManager.AppSettings["EmailAddress"];
            string fromName = System.Configuration.ConfigurationManager.AppSettings["EmailSender"];
            var fromAddress = new MailAddress(fromEmailAddress, fromName);
            var toAddress = toName != null ? new MailAddress(toEmailAddress, toName) : new MailAddress(toEmailAddress);

            var message = new MailMessage(fromAddress, toAddress)
           {
               Subject = subject,
               Body = msg
           };

            _emailManager.AddToQueue(message);

            return true;
        }
    }
}
